import {form} from "../config/index.js";

export default {
    template: `
         <el-dialog
            v-model="visible"
            :title="title"
            width="40%"
          >
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
                <el-form-item label="任务名称" prop="name">
                    <el-input clearable v-model="formData.name" />
                </el-form-item>
                <el-form-item label="任务标识" prop="tag">
                    <el-input clearable v-model="formData.tag" />
                </el-form-item>
                <el-form-item label="定时描述" prop="des">
                    <el-input clearable v-model="formData.des" @keydown.enter="operation.sendMsg" />
                </el-form-item>
                <el-form-item label="表达式" prop="code">
                    <el-input clearable v-model="formData.code" />
                </el-form-item>
                <el-form-item label="调用路径" prop="url">
                    <el-input clearable v-model="formData.url" />
                </el-form-item>
                <el-form-item label="凭证" prop="token">
                    <el-input clearable v-model="formData.token" />
                </el-form-item>
                <el-form-item label="任务状态" prop="state">
                    <el-select style="width: 100%" v-model="formData.state" placeholder="请选择" clearable>
                        <el-option label="启用" :value="true" />
                        <el-option label="禁用" :value="false" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="visible=false">取消</el-button>
                <el-button type="primary" @click="operation.save">保存</el-button>
              </span>
            </template>
        </el-dialog>
    `,
    setup(props, context) {
        const formRef = Vue.ref(null);
        const visible = Vue.ref(false)
        const title = Vue.ref("")
        const path = Vue.ref('https://gpt.lanmu.cc/api/openai/v1/chat/completions')
        const order = Vue.ref("生成定时任务的表达式，例如：每天凌晨1点执行一次，直接告诉我: 0 0 1 * * ?，这样即可，不要加额外的内容")
        const pass = Vue.ref("lanmuc")
        const operation = {
            save: async () => {
                (await getRef(formRef)).validate(async (valid) => {
                    if (valid) {
                        context.emit("save", form.formData)
                    }
                })
            },
            sendMsg: async () => {
                form.formData.code = ''
                fetch(path.value, {
                    method: 'POST',
                    body: JSON.stringify({
                        "messages": [
                            {
                                "role": "system",
                                "content": order.value
                            },
                            {
                                "role": "system",
                                "content": `事件名为:${form.formData.tag}`
                            },
                            {
                                "role": "system",
                                "content": `执行操作为:UPDATE cron SET version = version + 1 WHERE tag = '${form.formData.tag}' and state =TRUE;`
                            },
                            {
                                "role": "user",
                                "content": form.formData.des
                            }
                        ],
                        "max_tokens": 2000,
                        "stream": true,
                        "model": "gpt-3.5-turbo-0301",
                        "temperature": 0.2,
                        "presence_penalty": 2
                    }),
                    headers: {Authorization: `Bearer nk-${pass.value}`},
                })
                    .then(response => {
                        const reader = response.body.getReader();
                        return new ReadableStream({
                            start(controller) {
                                function push() {
                                    reader.read().then(({done, value}) => {
                                        if (done) {
                                            controller.close();
                                            return;
                                        }
                                        controller.enqueue(value);
                                        push();
                                    });
                                }

                                push();
                            },
                        });
                    })
                    .then(stream => new Response(stream))
                    .then(response => {
                        let endStr = '';
                        const reader = response.body.getReader();

                        function read() {
                            reader.read().then(({done, value}) => {
                                if (done) {
                                    return;
                                }
                                const text = endStr + new TextDecoder('utf-8').decode(value);
                                //使用data:分割
                                text.split('data:').filter(e => e).forEach((item, index) => {
                                    if (item.endsWith('[DONE]\n\n')) return
                                    try {
                                        let data = JSON.parse(item)
                                        form.formData.code += data?.choices[0]?.delta?.content ?? ''
                                    } catch (e) {
                                        endStr = item
                                    }
                                })
                                read();
                            });
                        }

                        read();
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            }
        }
        Vue.watch(visible, async val => val || (await getRef(formRef)).resetFields())
        return Object.assign({
            visible,
            title,
            formRef,
            operation
        }, form)
    }
}